import service from './axios';

// 方法映射
const methodEnum = {
  get: (url: string, params = {}) =>
    service.get(url, { params }).then((res) => res.data),

  post: (url: string, data = {}) =>
    service
      .post(url, data, {
        headers: { 'Content-Type': 'application/json' },
      })
      .then((res) => res?.data),

  put: (url: string, data = {}) =>
    service
      .put(url, data, {
        headers: { 'Content-Type': 'application/json' },
      })
      .then((res) => res.data),

  upload: (url: string, data: { file: any }) => {
    const { file } = data;
    const formData = new FormData();

    // 添加文件对象的所有属性
    for (const key in file) {
      if (Object.prototype.hasOwnProperty.call(file, key)) {
        formData.append(key, file[key]);
      }
    }
    // 添加文件本身
    formData.append('file', file);

    return service
      .post(url, formData, {
        headers: { 'Content-Type': 'multipart/form-data' },
      })
      .then((res) => res.data);
  },
};

// 支持的请求方法类型
type Method =
  | 'get'
  | 'post'
  | 'upload'
  | 'put'
  | 'GET'
  | 'POST'
  | 'UPLOAD'
  | 'PUT';

// 请求数据类型
type RequestData<T = any> = {
  method: Method;
  params?: T;
};

// 请求方法
const request = (url: string, requestData: RequestData): Promise<any> => {
  const { method, params } = requestData;
  const normalizedMethod = method.toLowerCase() as keyof typeof methodEnum;

  if (!methodEnum[normalizedMethod]) {
    return Promise.reject(new Error(`Unsupported method: ${method}`));
  }

  return methodEnum[normalizedMethod](url, params);
};

export default request;
